package com.qf.openapi.web.master.Interceptor;

import cn.hutool.crypto.digest.DigestUtil;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.SessionKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
public class PlateFormInterceptor implements HandlerInterceptor {
    UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求进入拦截器，url={}", request.getRequestURI());
        //1.如果用户登录过，session中已经保存了用户的登录状态，这时如果再访问/login.html，直接重定向到plateform.html
        HttpSession session = request.getSession();
        Object sessionUser = session.getAttribute(SessionKey.user_Login_Session_Key);
        if (sessionUser != null) {
            log.debug("用户已经登录过了，session中有user对象，直接重定向到/plateform.html");
            response.sendRedirect("/plateform.html");
        }
        //2，用户的浏览器没有登录过，但是浏览器的cookie中已经保存了免登录信息，这种情况校验免登录信息正确性，如果正确，直接重定向到 /plateform.html
        Cookie[] cookies = request.getCookies();//获取本次请求头中cookie数据
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                //判断cookieName是不是免登录的cookie
                if (SessionKey.user_AutoLogin_Cookie_Key.equals(cookieName)) {
                    //找到了进行免登录
                    String cookieValue = cookie.getValue();
                    String[] split = cookieValue.split("-");
                    String username = split[0];
                    String password = split[1];
                    String md5Password = DigestUtil.md5Hex(password);
                    //依赖userService进行用户和密码的校验
                    User user = userService.getUserByName(username);
                    String password1 = user.getPassword();
                    if (user != null && md5Password.equals(password1)) {
                        //免登录校验通过，在session中设置登录状态，重定向到/plateform.html
                        session.setAttribute(SessionKey.user_Login_Session_Key, user);
                        response.sendRedirect("/plateform.html");
                        log.debug("浏览器携带免登录cookie，校验通过重定向到");
                        return false;
                    }

                }
            }
            log.debug("浏览器没有携带免登录cookie直接进入登录页");
            return true;
        } else {
            log.debug("浏览器没有携带免登录cookie直接进入登录页");
            return true;
        }

    }
}
